import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, DeviceEventEmitter, TextInput, ScrollView,Modal,
	Alert,PixelRatio
} from 'react-native';
import { API, API_GENERATE } from '../../../../config/api';
import HTTP from '../../../../utils/http';
import ValidateDataUtil from '../../../../utils/ValidateDataUtil';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js'
import ToastUtil from '../../../../utils/toast';
import { LargeBtn } from '../../../../component/Store.js';
import Dictionary from '../../../../utils/dictionary';
import { ProductEditing } from '../../../customer-management/highSeas/_components/ProductEditing';
import ModalAreaComponent from '../../../../component/ModalAreaComponent.js';
const scale = GLOBAL.SCALE;
const arrowLeft = require('../../../../imgs/sanjiao3.png');

export class EnterpriseEditContactPage extends Component {

	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		const { countryCode, vo, addressCodeParam } = params;

		return {
			headerTitle: '用户信息',
			headerLeft: <Common type="headLeft" onPress={() => {
				navigation.goBack()
			}} color='#fff' />,
			headerTintColor: style.color.white,
			headerStyle: {
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		const { choice, vo, companyName, addressObj,companyId } = this.props.navigation.state.params || {};
		this.state = {
			addressStr: vo ? vo.contactorAddress : '',
			modalObj: {
				currSelectIndex: -1,
				currTitle: '',
				currlistData: [],
				currCb: null,
				currIsVisible: false,
			},
			contractType:[{dictName:'不带入'}],
			selectIndex:0,
			goodsModal:false,
			searching:true,
			goodsTreeList:[],
			modalVisible:false,
			mainMethodText:'请关联经营品类',
			mainMethodTextCheck:[],
			modalAreaVisible:false,
			areaModalProp: {
				addressInfo: null,
			}
		}
		this.sendData = {
			contactorList: [],
			bizType: 'COMPANY_CONTACT_INFO',
			companyId:companyId||vo.companyId,
			companyInfoVO: {
				companyId:companyId||vo.companyId,
				companyName: companyName,
			},
			companyContactorGoodsVOList:[]
		};
		this.sendData.contactorList[0] = vo || {};
		this.sendData.contactorList[0].companyId = companyId||vo.companyId
		this.companyId = companyId||vo.companyId;
		this.choice = choice;
	}
	async componentWillMount() {
		let contractType = await Dictionary.get("CC_CONTACTOR_ATTACHED");
		this.setState({contractType})
		if(this.sendData.contactorList.length>0&&this.sendData.contactorList[0].attachedFlag){
			this.setState({
				selectIndex:this.sendData.contactorList[0].attachedFlag-1
			})
		}
		this._getGoodsData()
		this._getAddressInfo();
	}
	componentWillUnmount () {
		DeviceEventEmitter.emit('customerAddItemInfo', { bizType: 'COMPANY_CONTACT_INFO', companyId: this.companyId });
	}
	async _getGoodsData (searchKey,type) {
		let responseData = await HTTP.POST(API_GENERATE(API.COMPANY_GOODSTREE_LIST), { companyId: this.companyId, searchKey: searchKey?searchKey.searchCode:null, corpId: this.choice.corpId,contractorId: this.sendData.contactorList[0].contactorId});
		if(type!='search'){
			this._getGoodsCode(responseData)
		}
		this.setState({ searching: false, goodsTreeList: responseData })
	}
	cancelPress () {
		this.setState({ modalVisible: !this.state.modalVisible });
	}
	openModal (title, listData, index, cb) {
		let { modalObj } = this.state;
		modalObj.currIsVisible = true;
		modalObj.currSelectIndex = index;
		modalObj.currTitle = title;
		modalObj.currlistData = listData;
		modalObj.currCb = cb;
		this.setState({ modalObj }, () => {
		});
	}
	getType = (index) => {
		this.setState({ selectIndex: index}, () => {
			this.closeModal()
		});
	}
	closeModal = () => {
		let { modalObj } = this.state;
		modalObj.currIsVisible = false;
		this.setState({ modalObj });
	}
	_getGoodsCode = (data) => {
		let mainMethodTextCheck = [];
		this.sendData.companyContactorGoodsVOList = []
		// this.objectId = [];
		for (var i = 0; i < data.length; i++) {
		  const element = data[i].goodsList
		  let selectLength = 0
		  for (var j = 0; j < element.length; j++) {
			const subData = element[j]
			if (subData.noCheckFlag=='1'&&subData.select!==false){
				subData.select = true
			}
			if (subData.select) {
			  this.sendData.companyContactorGoodsVOList.push(
				  {
					objectId: subData.goodsCode,
					objectType: "CATEGORY"
				  }
			  )
			  mainMethodTextCheck.push(subData.goodsName);
			  selectLength++
			}
			if(selectLength===element.length){
				data[i].select=true
			}
		  }
		}
		this.setState({ 
			mainMethodTextCheck,
			modalVisible: false,
			mainMethodText: mainMethodTextCheck.length && mainMethodTextCheck.join(',')
		})
		console.log(mainMethodTextCheck)
	}
	async _getAddressInfo () {
		let mapData = require('../../../../data/map.json');
		this.setState({
			areaModalProp: {
				addressInfo: mapData.data,
				cancelPress: () => {
					this.setState({
						modalAreaVisible: false
					});
				},
				confirmPress: (data) => {
					const { province, city, area } = data;
					const areaText = `${province.areaName}${city.areaName ? ('，' + city.areaName) : ''}${area.areaName ? ('，' + area.areaName) : ''}`;

					this.sendData.contactorList[0].contactorAddress = areaText || '';

					this.setState({
						modalAreaVisible: false,
						addressStr:areaText
					});
				},
			},
			loaded: false
		})
	}
	render () {
		const { contactorName, mobileNo, email,contactorPosition} = this.sendData.contactorList[0];
		let { addressStr,modalObj,contractType,selectIndex,modalVisible,goodsTreeList,mainMethodText,modalAreaVisible,areaModalProp} = this.state;
		return (
			<ScrollView style={styles.scrollView} keyboardShouldPersistTaps={'handled'} keyboardDismissMode={'on-drag'}>
				<View style={styles.container}>
					<View style={styles.wrap}>
						<View style={{ flex: 1, paddingTop: 10 * scale }}>

							<View style={styles.field}>
								<Text style={styles.fieldcolor}>*</Text>
								<View style={styles.fieldRight}>
									<Text style={styles.lableText}>联系人</Text>
									<TextInput
										ref="bonusInput"
										style={styles.textInput}
										underlineColorAndroid='transparent'
										placeholder={"请输入联系人"}
										placeholderTextColor="#404040"
										maxLength={100}
										editable={true}
										defaultValue={contactorName}
										onChangeText={(txt) => {
											this.sendData.contactorList[0].contactorName = txt;
										}}
									/>
								</View>
							</View>

							<View style={styles.field}>
								<Text style={styles.fieldcolor}>*</Text>
								<View style={styles.fieldRight}>
								<Text style={styles.lableText}>电话</Text>
								<TextInput
									ref="mobileNoInput"
									keyboardType="numeric"
									style={styles.textInput}
									underlineColorAndroid='transparent'
									placeholder={"请输入联系电话"}
									placeholderTextColor="#404040"
									editable={true}
									defaultValue={mobileNo}
									onChangeText={(txt) => {
										this.sendData.contactorList[0].mobileNo = txt;
									}}
								/>
								</View>
							</View>
							
							{/* <View style={styles.field}>
								<Text style={styles.lableText}>部门</Text>
								<TextInput
									ref="bonusInput"
									style={styles.textInput}
									underlineColorAndroid='transparent'
									placeholder={"请输入部门"}
									placeholderTextColor="#404040"
									maxLength={100}
									editable={true}
									defaultValue={contactorDepart}
									onChangeText={(txt) => {
										this.sendData.contactorList[0].contactorDepart = txt;
									}}
								/>
							</View> */}
							<TouchableOpacity style={styles.field}
								 onPress={() => this.setState({ modalVisible: true })}
							>
								<Text style={styles.fieldcolor}>*</Text>
								<View style={styles.fieldRight}>
								<Text style={styles.lableText}>经营品类</Text>
								<View style={styles.textInputAddress}>
									<Text style={{
										fontSize: 13 * scale,
										color: '#404040',
										paddingLeft:5*scale,
										flex:1
									}} numberOfLines={1}>{mainMethodText||'请关联经营品类'}</Text>
									<View style={styles.textInputIcon} >
										<Image source={arrowLeft} style={styles.arrowLeft} />
									</View>
								</View>
								</View>
							</TouchableOpacity>
							<TouchableOpacity style={styles.field}
								onPress={() => {
									this.openModal('请选择合同使用类型', contractType, selectIndex, this.getType)
								}}
							>
								<Text style={styles.fieldcolor}>*</Text>
								<View style={styles.fieldRight}>
								<Text style={styles.lableText}>合同使用</Text>
								<View style={styles.textInputAddress}>
									<Text style={{fontSize: 13 * scale,color: '#404040',paddingLeft:5*scale}}>{contractType[selectIndex].dictName}</Text>
									<View style={styles.textInputIcon} >
										<Image source={arrowLeft} style={styles.arrowLeft} />
									</View>
								</View>
								</View>
							</TouchableOpacity>
							<View style={styles.field}>
							<Text style={styles.fieldcolor}></Text>
								<View style={styles.fieldRight}>
								<Text style={styles.lableText}>职位</Text>
								<TextInput
									ref="bonusInput"
									style={styles.textInput}
									underlineColorAndroid='transparent'
									placeholder={"请输入职位信息"}
									placeholderTextColor="#404040"
									maxLength={100}
									editable={true}
									defaultValue={contactorPosition}
									onChangeText={(txt) => {
										this.sendData.contactorList[0].contactorPosition = txt;
									}}
								/>
								</View>
							</View>
							<View style={styles.field}>
							<Text style={styles.fieldcolor}></Text>
								<View style={styles.fieldRight}>
								<Text style={styles.lableText}>邮箱</Text>
								<TextInput
									ref="emailInput"
									keyboardType="email-address"
									style={styles.textInput}
									underlineColorAndroid='transparent'
									placeholder={"请输入邮箱"}
									placeholderTextColor="#404040"
									editable={true}
									defaultValue={email}
									onChangeText={(txt) => {
										this.sendData.contactorList[0].email = txt;
									}}
								/>
								</View>
							</View>
							<TouchableOpacity style={styles.field}
								 onPress={() => this.setState({ modalAreaVisible: true })}
							>
								<Text style={styles.fieldcolor}></Text>
								<View style={styles.fieldRight}>
								<Text style={styles.lableText}>地址</Text>
								<View style={styles.textInputAddress}>
									<Text style={{
										fontSize: 13 * scale,
										color: '#404040',
										paddingLeft:5*scale,
										flex:1
									}} numberOfLines={1}>{addressStr}</Text>
									<View style={styles.textInputIcon} >
										<Image source={arrowLeft} style={styles.arrowLeft} />
									</View>
								</View>
								</View>
							</TouchableOpacity>
							{/* <View style={styles.field}>
								<Text style={styles.fieldcolor}></Text>
								<View style={styles.fieldRight}>
								<Text style={styles.lableText}>地址</Text>
								<View style={styles.textInputAddress}>
									<TextInput
										ref="detailAddress"
										style={[styles.textInput]}
										underlineColorAndroid='transparent'
										placeholder={"请输入地址"}
										placeholderTextColor="#404040"
										editable={true}
										defaultValue={addressStr}
										onChangeText={(txt) => {
											this.sendData.contactorList[0].contactorAddress = txt;
										}}
									/>
								</View>
								</View>
							</View> */}
						</View>
						<LargeBtn text={'提交'} onPress={() => this._didPressLargeBtn()} />
					</View>
				</View>
				<Common type="modal" demoData={(
					<Common type="listRadio" selectIndex={modalObj.currSelectIndex} title={modalObj.currTitle} listData={modalObj.currlistData || []} selectCallBack={modalObj.currCb} />
				)} isVisible={modalObj.currIsVisible} closeCallballFn={this.closeModal} />
				<Modal animationType={"fade"}
					transparent={true}
					visible={modalVisible}>
					<View style={styles.back}>
						<TouchableOpacity activeOpacity={1} style={styles.bg} onPress={() => { this.cancelPress() }}>
						</TouchableOpacity>
						<ProductEditing
							searchPress={(searchCode) => {
								this.setState({
								searching: true
								}, () => {
									this._getGoodsData(searchCode,'search')
								})
							}}
							data={goodsTreeList || []}
							leftBtnsList={{
								btnText: '没有品类?',
								btnFun: () => {Alert.alert('提示','仅支持关联企业当前所有绑定的经营品类，若没有，请先维护企业经营品类关联。')}
							}}
							rightBtnsList={[{
								btnText: '确认关联',
								btnFun: (data) =>{
									this._getGoodsCode(data)
								}
								
							}]}
							secondRight={true}
							optionBox={true}
							searching={this.state.searching}
							/>
					</View>
					</Modal>
				{areaModalProp.addressInfo ? <ModalAreaComponent {...areaModalProp} selectCustom={true} visible={modalAreaVisible} /> : null}
			</ScrollView>
		);
	}

	/**
	 * 点击底部按钮
	 */
	async _didPressLargeBtn () {
		const { contactorName, mobileNo,email} = this.sendData.contactorList[0];
		if (ValidateDataUtil.isEmpty(contactorName)) {
			Alert.alert('请填写联系人姓名');
			return;
		}
		if (ValidateDataUtil.isEmpty(mobileNo)) {
			Alert.alert('请填写联系人电话');
			return;
		}
		else {
			if (!ValidateDataUtil.isPhone(mobileNo)) {
				Alert.alert('请输入正确手机号格式');
				return;
			}
		}
		if(this.sendData.companyContactorGoodsVOList.length===0){
			Alert.alert('请选择经营品类');
			return;
		}
		// else{
		// 	if(!ValidateDataUtil.isEmail(email)){
		// 		Alert.alert('请输入正确邮箱格式');
		// 		return;
		// 	}
		// }
		this.setState({
			loaded: true
		})
		console.log(this.sendData)
		this.sendData.contactorList[0].attachedFlag = this.state.selectIndex+1;
		this.sendData.corpId = this.choice.corpId;
		const responseData = await HTTP.POST(API_GENERATE(API.UPDATE_CUSTOMER_INFO), this.sendData);
		this.setState({
			loaded: false
		})

		if (responseData) {
			ToastUtil.showSuccess('您申请添加的联系人已提交');
			this.timer = setTimeout(() => {
				this.props.navigation.navigate('EnterpriseDetailsPage')
				if(this.props.navigation.state.params.init){
					this.props.navigation.state.params.init()
				}
				DeviceEventEmitter.emit('qycyUpdate');
			}, 800)
		}
	}

	// 返回上一个页面
	_goBack = () => {
		const { navigate } = this.props.navigation;
		navigate('EnterpriseDetailsPage', {
			goBack: false
		});
	}

}

const styles = StyleSheet.create({
	scrollView: {
		flex: 1,
		backgroundColor: '#fff',
	},
	container: {
		flex: 1,
		alignItems: 'center',
		backgroundColor: '#fff',
	},
	wrap: {
		height: GLOBAL.SCREEN_HEIGHT - 120,
		width: 345 * scale,
	},
	closeText: {
		fontSize: 36 * scale,
		color: '#000'
	},
	closeTextCell: {
		position: 'absolute',
		left: 8,
		top: 0,
	},
	textInputView: {
		alignItems: 'center',
		justifyContent: 'space-between',
		flexDirection: 'row',
		flexWrap: 'wrap'
	},
	textInputAddress:{
		alignItems: 'center',
		flex:1,
		justifyContent: 'space-between',
		flexDirection: 'row',
		flexWrap: 'wrap'
	},
	textInputIcon: {
		alignItems: 'center',
		justifyContent: 'flex-end',
		flexDirection: 'row',
		// height: 22 * scale,
		width: 52 * scale,
		paddingRight:10*scale
	},
	field: {
		flexDirection:'row',
		marginBottom: 12 * scale,
		// alignItems:'center',
		paddingTop:10*scale,
	},
	fieldRight:{
		borderBottomColor: '#000',
		borderBottomWidth: 1,
		paddingBottom:10*scale,
		flexDirection:'row',
		alignItems:'center',
		flex:1,
	},
	lableText: {
		fontWeight:'600',
		fontSize: 14 * scale,
		color: '#000',
		width:80*scale,
	},
	arrowLeft:{
		width: 10 * scale,
		height: 15 * scale,
		transform:[{rotate:'90deg'}]
	},
	fieldcolor:{
		color:'red',
		marginRight:5*scale,
		width:8*scale
	},
	textInput: {
		borderWidth: 0,
		fontSize: 13 * scale,
		width: '100%',
		padding: 0,
		alignSelf: 'center',
	},
	back: {
		width: 375 * scale,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		height: GLOBAL.SCREEN_HEIGHT,
		flex: 1
	  },
	bg: {
		width: 375 * scale,
		height: '20%',
	  },
})